package com.company.ljh.easy;

/**
 * @description:
 * @projectName:leet_code
 * @see:com.company.ljh.easy
 * @author:ljh
 * @createTime:2022/3/25 14:40
 * @version:1.0
 */
public class 移动零 {
    /**
     * 冒泡法
     * @param nums
     */
    public static void moveZeroes(int[] nums) {
        int end = nums.length;
        //优化 先判断后面是否已经是都为0
        for (int i = nums.length-1; i >= 0; i--) {
            if (nums[i] == 0){
                end--;
            }
            else {
                break;
            }
        }
        int i = 0;
        while (i < end){
            if (nums[i] == 0){
                //1.交换方式采用冒泡式左右替换，效率低
//                for (int j = i;j < end;j++){
//                    int temp = nums[j];
//                    nums[j] = nums[j+1];
//                    nums[j+1] = temp;
//                }
            }else {
                i++;
            }
        }

        System.out.println(nums);
    }

    /**
     * 双指针法，左指针左边为非0数，右指针右边为未处理数据，左右指针中间为0
     * 当左指针遇到0，交换左右指针数据右指针+1
     * 当左指针遇到非0，左指针+1
     * 当左指针>右指针，右指针=左指针
     *
     */
    public static void moveZeroes2(int[] nums) {
        int left = 0;
        int right = 0;
        while (right < nums.length){
            if (nums[left] != 0){
                left++;
                if (left > right){
                    right = left;
                }
            }else {
                nums[left] = nums[right];
                nums[right] = 0;
                right++;
            }
        }
    }

    /**
     * 双指针法2 如果当前值非0，则与第一个指针的数据交换,i到start之间的数都是0
     * @param
     */
    public void moveZeroes3(int[] nums) {
        int start = 0;
        for(int i =0;i<nums.length;i++){
            if(nums[i] != 0){
                int temp = nums[i];
                nums[i] = nums[start];
                nums[start++] = temp;
            }
        }
    }
    public static void main(String[] args) {
        int nums[] = {0,1,0,3,12};
        moveZeroes(nums);
        System.out.println(nums);
    }
}
